package com.example.movie.ui.user.search

import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.movie.R
import com.example.movie.common.dsl.afterTextChanged
import com.example.movie.data.movie.factory.SearchViewModelFactory
import com.example.movie.data.movie.model.SearchViewModel
import com.example.movie.ui.user.search.adapter.SearchResultAdapter
import kotlinx.android.synthetic.main.fragment_search.*

class SearchActivity : AppCompatActivity() {

    private val searchViewModel: SearchViewModel by viewModels(factoryProducer = { SearchViewModelFactory() })

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.fragment_search)
        setObservers()
        initView()
    }

    private fun setObservers() {
        searchViewModel.searchResult.observe(this, {
            with(it.success){
                this?.let {
                    search_result.apply {
                        this.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
                        val searchResultAdapter = SearchResultAdapter(it,this@SearchActivity)
                        this.adapter = searchResultAdapter
                        searchResultAdapter.notifyDataSetChanged()
                    }
                }
            }

        })
    }

    private fun initView() {
        input.afterTextChanged{
            if (it.isNotBlank()){
                searchViewModel.search(it)
            }
        }

        cancel.setOnClickListener {
           onBackPressed()
        }
    }

}